<template>
  <div class="category-admin">
    <h3>商品分类管理</h3>
    <el-card>
      <div slot="header" class="clearfix">
        <el-button type="primary" @click="handleAdd">
          添加分类
        </el-button>
      </div>

      <el-table :data="categoryiesTree.categories" border :header-cell-style="{ background: '#F5F6FA', color: '#000' }"
        style="width: 100%" row-key="categoryId" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="categoryName" label="分类名称"></el-table-column>
        <el-table-column prop="icon" label="分类图片"></el-table-column>
        <el-table-column prop="sort" label="排序" width="100"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" @click="handleAddChild(scope.row)">添加子分类</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <div class="footer">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="page.pageNum" :page-sizes="[5, 12, 18, 20]" :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next" :total="categoryiesTree.total" class="pagination">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName"></el-input>
        </el-form-item>
        <el-form-item label="上级分类" prop="parentId">
          <el-cascader v-model="form.parentId" :options="categoryCascader" :props="{ checkStrictly: true }"
            @change="CasChange"></el-cascader>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCategoriesTree, getCategoriesCascader, addCategory, romoveCategory, editCategory } from '@/apis/category'


export default {
  name: 'CategoryAdmin',
  data() {
    return {
      categoryiesTree: {},
      categoryCascader: [],
      page: {
        pageNum: 1,
        pageSize: 5
      },
      dialogVisible: false,
      dialogTitle: '添加分类',
      form: {
        categoryId: null,
        parentId: null,
        categoryName: '',
        sort: 0
      },
      rules: {
        categoryName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ],
        sort: [
          { type: 'number', required: true, message: '请输入排序值', trigger: 'change' }
        ]
      }
    }
  },
  computed: {

  },
  created() {
    //发起查询数据请求
    this.getCategoriesTree()
    this.getCategoryCascader()
  },
  methods: {
    //获取树状数据
    async getCategoriesTree() {
      const res = await getCategoriesTree(this.page)
      this.categoryiesTree = res.data
    },

    //获取级联选择器数据
    async getCategoryCascader() {
      const res = await getCategoriesCascader()
      this.categoryCascader = res.data
    },

    // 处理分页大小变化事件
    handleSizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getCategoriesTree();
    },

    // 处理当前页码变化事件
    handleCurrentChange(pageNum) {
      this.page.pageNum = pageNum;
      this.getCategoriesTree();
    },

    //级联选择器change事件
    CasChange() {
      if (Array.isArray(this.form.parentId) && this.form.parentId.length > 0) {
        this.form.parentId = this.form.parentId[this.form.parentId.length - 1]
      }
    },

    //弹出添加分类弹窗
    handleAdd() {
      this.dialogTitle = '添加分类'
      this.form = {
        categoryId: null,
        parentId: null,
        categoryName: '',
        sort: 0
      }
      this.dialogVisible = true
    },

    // 弹出添加子分类弹窗
    handleAddChild(row) {
      this.dialogTitle = '添加子分类'
      this.form = {
        categoryId: null,
        parentId: row.categoryId,
        categoryName: '',
        sort: 0
      }
      this.dialogVisible = true
    },

    //弹出编辑分类弹窗
    handleEdit(row) {
      this.dialogTitle = '编辑分类'
      this.form = {
        categoryId: row.categoryId,
        // 编辑时默认不修改父级，如需修改可通过级联重新选择
        parentId: row.parentId || null,
        categoryName: row.categoryName,
        sort: row.sort
      }
      this.dialogVisible = true
    },

    handleDelete(row) {
      this.$confirm('确认删除该分类吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        romoveCategory(row.categoryId).then(() => {
          // 重新加载列表和级联数据
          this.getCategoriesTree()
          this.getCategoryCascader()
        })
      })
    },

    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const payload = {
            categoryName: this.form.categoryName,
            sort: this.form.sort,
            parentId: this.form.parentId
          }

          // 有 categoryId 为编辑，否则为新增（包括新增子分类）
          const request = this.form.categoryId
            ? editCategory(this.form.categoryId, payload)
            : addCategory(payload)

          request.then(() => {
            this.dialogVisible = false
            // 刷新树数据和级联数据
            this.getCategoriesTree()
            this.getCategoryCascader()
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.category-admin {
  padding: 20px;
}
</style>
